/*
 * @since 17 may 2012
 * @author Koen Ursem
 */
package gui;

//imports for protocol
import Protocol.AccountManagementRequestPacket;
import Protocol.AccountManagementResponsePacket;
import config.Content;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.*;

/** This class is responsible for creating the User Administration Panel in the masterclient
 * @version 0.9b
 * @author Koen Ursem
 */
public class UserAdministrationPanel extends JPanel implements ActionListener {

    //the pannels for the layout
    protected JPanel LeftPanel;
    protected JPanel RightPanel;
    //the form-elements used for the management form
    private JLabel Jtitle, Jusername, Jpassword, Jadmin, JloginId, JloginIdOld;
    private JTextField username, loginid, loginidold;
    private JPasswordField password;
    private JCheckBox admin;
    private JButton adduser, edit, delete;
    private JScrollPane scrollPane;

    /*
     * constructor 
     * @author Koen Ursem
     */
    public UserAdministrationPanel() {

	super(); // Temporary LayoutManager, wil consider another one later.
	//pannel for the left side 
	setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
	LeftPanel = new JPanel();
	LeftPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
	//panel for the right side
	RightPanel = new JPanel();
	RightPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
	RightPanel.setLayout(new GridLayout(18, 1, 10, 10));
	//add the panels
	this.add(LeftPanel);
	this.add(RightPanel);
	//load the page data
	init();
    }

    /*
     * requests all data to create the page @author Koen Ursem
     */
    private void init() {
	//userdata request
	requestUserList();
	//buttons and text fields
	createForms();
    }

    /*
     * requests the userlist from the database and creates a table in the left
     * panel @author Koen Ursem
     */
    private void requestUserList() {
	//start packet as null to avoid failed try errors
	AccountManagementResponsePacket response = null;
	try {
	    //set packet type
	    AccountManagementRequestPacket request = new AccountManagementRequestPacket(0);
	    //send packet and listen for response
	    response = (AccountManagementResponsePacket) Content.connection.communicate(request);
	    //print message in console for testing or debugging
	    System.out.println("REQUESTED USERLIST FOR user administration pannel!");

	} catch (Exception ex) {
	    //when failing catch the error and print it in the console for problem resolving
	    Content.log.println("error");
	    System.out.print(ex);

	}

	//set the column names for the table
	String[] Columns = {"Windows Login ID", "Username", "Admin"};
	//create a arraylist from the results of the server
	ArrayList<String[]> info = response.getListWithAccount();
	//create an object of the arraylist for the JTable
	Object[][] data = TablePanel.convertListToData(info);

	//create the table with the data and colums
	JTable table = new JTable(data, Columns);
	table.setFillsViewportHeight(true);
	table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	//set width off the column rows
	table.getColumnModel().getColumn(0).setPreferredWidth(150);
	table.getColumnModel().getColumn(1).setPreferredWidth(100);
	table.getColumnModel().getColumn(2).setPreferredWidth(50);
	//add the table to the left panel
	LeftPanel.add(table.getTableHeader());
	LeftPanel.add(table);
	//set editing of table off
	table.setEnabled(false);
	
	//now that the table exists we can add the scrollbar to it
	scrollPane = new JScrollPane(table);
	scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	LeftPanel.add(scrollPane);

	//finaly we validate the content to show up right
	LeftPanel.revalidate();
    }

    /*
     * Creates the form for managing the users @author Koen Ursem
     */
    private void createForms() {

	//labels and input fields

	Jtitle = new JLabel("User management functions:");
	RightPanel.add(Jtitle);

	JloginIdOld = new JLabel("<html>Old Login ID (for edit only):<br/></html>");
	RightPanel.add(JloginIdOld);

	loginidold = new JTextField(10);
	RightPanel.add(loginidold);

	JloginId = new JLabel("<html>Login ID:</html>");
	RightPanel.add(JloginId);

	loginid = new JTextField(10);
	RightPanel.add(loginid);

	Jusername = new JLabel("Username:");
	RightPanel.add(Jusername);

	username = new JTextField(10);
	RightPanel.add(username);

	Jpassword = new JLabel("Password:");
	RightPanel.add(Jpassword);

	password = new JPasswordField(10);
	RightPanel.add(password);

	Jadmin = new JLabel("Admin:");
	RightPanel.add(Jadmin);

	admin = new JCheckBox();
	RightPanel.add(admin);

	//buttons and connected listeners on those buttons

	adduser = new JButton("Add user");
	RightPanel.add(adduser);
	adduser.addActionListener(this);

	edit = new JButton("Edit user");
	RightPanel.add(edit);
	edit.addActionListener(this);

	delete = new JButton("Delete user");
	RightPanel.add(delete);
	delete.addActionListener(this);

    }

    /*
     * When button is pressed will communicate a request to the server to create a new
     * user @author Koen Ursem
     */
    private void pressedNewUser() {
	//collect the data from the form
	String adminstate = "0";
	String passwordstate = password.getText();
	String loginidstate = loginid.getText();
	String usernamestate = username.getText();
	if (admin.isSelected() == true) {
	    adminstate = "1";
	}

	//print the data in the console to check if its right
	System.out.println("ADD:" + adminstate + " " + passwordstate + " " + usernamestate);

	//put on null for start failue
	AccountManagementResponsePacket response = null;

	try {
	    //create packet
	    AccountManagementRequestPacket request = new AccountManagementRequestPacket(1);
	    //packet type
	    request.setTypeOfManagementPacket(1);
	    //bind packet values
	    request.setAccountInformation(loginidstate, usernamestate, passwordstate, adminstate);
	    //send packet and listen for answer
	    response = (AccountManagementResponsePacket) Content.connection.communicate(request);
	    //print message in console for admin and debugging
	    System.out.println("ADDED new user!");

	} catch (Exception ex) {
	    //catch exeption and print error for debugging
	    Content.log.println("error");
	    System.out.print(ex);
	}

	//reload the page to see the changes that are made
	refresh();
    }

    /*
     * Runs when the edit button is pressed @author Koen Ursem
     */
    private void pressedEditUser() {
	//collect the data from the form
	String adminstate = "0";
	String passwordstate = password.getText();
	String loginidstate = loginid.getText();
	String loginidoldstate = loginidold.getText();
	String usernamestate = username.getText();
	if (admin.isSelected() == true) {
	    adminstate = "1";
	}

	if (!"".equals(loginidoldstate)) {
	    //print the collected data
	    System.out.println("EDIT:" + adminstate + " " + passwordstate + " " + usernamestate + " " + loginidoldstate);

	    //add server conection and request/response action
	    AccountManagementResponsePacket response = null;

	    try {
		//create packet
		AccountManagementRequestPacket request = new AccountManagementRequestPacket(2);
		//set packet type
		request.setTypeOfManagementPacket(2);
		//bind packet parameters for user info
		HashMap<String, String> map = new HashMap();
		map.put("windowsLogingID", loginidoldstate);
		request.setAccountInformation(map);

		//bind packet parameters for edit with checking if not empty
		HashMap<String, String> mapEdit = new HashMap();
		if (!"".equals(loginidstate)) {
		    mapEdit.put("windowsLogingID", loginidstate);
		    System.out.println(loginidstate + "E####");
		}
		if (!"".equals(usernamestate)) {
		    mapEdit.put("username", usernamestate);
		}
		if (!"".equals(passwordstate)) {
		    mapEdit.put("password", passwordstate);
		}
		mapEdit.put("usertype", adminstate);

		request.setAlterAccountToo(mapEdit);
		//send packet and listen for answer
		response = (AccountManagementResponsePacket) Content.connection.communicate(request);
		//print message for admin or debugging
		System.out.println("CHANGED user!");

	    } catch (Exception ex) {
		//catch error on failure and print error for admin or debugging
		Content.log.println("error");
		System.out.print(ex);
	    }
	} else {
	    System.out.println("Cannot send without old userid!");
	}
	//reload page to see changes
	refresh();
    }

    /*
     * Runs when delete button is pressed @author Koen Ursem
     */
    private void pressedDeleteUser() {
	//collect the form data that is needed
	String loginidstate = loginid.getText();

	//print username to check
	System.out.println("DELETE:" + loginidstate);

	//create null value for packet to start with
	AccountManagementResponsePacket response = null;

	try {
	    //create packet type
	    AccountManagementRequestPacket request = new AccountManagementRequestPacket(3);
	    //set packet type
	    request.setTypeOfManagementPacket(3);
	    //add packet data
	    HashMap<String, String> map = new HashMap();
	    map.put("windowsLogingID", loginidstate);
	    request.setAccountInformation(map);
	    //send packet and listen for asnwer
	    response = (AccountManagementResponsePacket) Content.connection.communicate(request);
	    //print message for admin or debugging
	    System.out.println("DELETED user!");

	} catch (Exception ex) {
	    //catch errors and print error for admin or debugging
	    Content.log.println("error");
	    System.out.print(ex);
	}
	//reloads table and form to see changes
	refresh();
    }

    /*
     * Reloads the data of the panels in the page to see changes that are made
     * @author Koen Ursem
     */
    public void refresh() {
	//remove current data from the pannels
	LeftPanel.removeAll();
	RightPanel.removeAll();
	try {
	    remove(scrollPane);
	} catch (Exception ex) {
	    //catch if scrollPane does not exist
	}

	//update the user interface of java to be empty
	updateUI();

	//load the data for the panels again
	init();

	//update the user interface of java again to be filled
	updateUI();
    }

    /*
     * Action handler for when a button is pressed and the action for pressing
     * it @author Koen Ursem
     */
    @Override
    public void actionPerformed(ActionEvent e) {
	//if statements when triggered will run the named function
	if (e.getSource() == adduser) {
	    pressedNewUser();
	}
	if (e.getSource() == edit) {
	    pressedEditUser();
	}
	if (e.getSource() == delete) {
	    pressedDeleteUser();
	}
    }
}
